package room_event

import (
	"encoding/json"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/chat"
	"longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/pkg/common/helper/blackWorlds"
	"longmen/server/pkg/db/mysql/db_live"
	pb "longmen/server/pkg/protobuf"
)

type SendProPsReq struct {
	PropsId   uint32 `json:"props_id"`   //Id 道具Id
	PropsType uint32 `json:"props_type"` // 道具类型
	Count     uint32 `json:"count"`      //数量
	UserId    uint32 `json:"user_id"`
	Type      string `json:"type"`
	Content   string `json:"content"`
}

type SendProPsResp struct {
	*SendProPsReq
	Vip   int   `json:"vip"`
	Level int32 `json:"level"`
	Role  int32 `json:"role"`
}

type SendProPsHistory struct {
	UserID    int    `json:"user_id"`    // 会员Id
	Count     uint32 `json:"count"`      // 数量
	PropsID   uint32 `json:"props_id"`   // Id 道具Id
	Type      string `json:"type"`       // 消息类型
	PropsType uint32 `json:"props_type"` // 道具类型
	Content   string `json:"content"`    // 消息内容
}

func handlingPropsMessage(user *chat.ClientUser, b []byte) (ret *pb.CallbackResp, err error) {

	PropsReq := &SendProPsReq{}
	ret = &pb.CallbackResp{}
	if err = json.Unmarshal(b, PropsReq); err != nil {
		return utils.CallbackFailResp(ret, err.Error()), err
	}
	PropsReq.UserId = uint32(user.UserId)
	if PropsReq.PropsType == 101 || PropsReq.PropsType == 100 {
		if user.Role != 3 { //不是房管的时候才检测
			PropsReq.Content = blackWorlds.BlackWorInstance.ReplaceWithAsterisk(PropsReq.Content)
		}
		//检测数量并消费
		if db_live.PropsSubtract(user.UserId, int(PropsReq.PropsId), int(PropsReq.PropsType), int(PropsReq.Count)) == 0 {
			global.Log.Infof("danmu PROPS QUANTITY NOT ENOUGH,PARAMETER USER ID:=%d, PROPS ID:=%d, QUANTITY:=%d", user.UserId, PropsReq.PropsId, PropsReq.Count)
			return utils.CallbackRespWithCode(imsdk.TIM_SEND_PROPS_ERR, "数量不足", ret), nil
		}
		resp := SendProPsResp{
			SendProPsReq: PropsReq,
			Vip:          user.Vip,
			Role:         user.Role,
			Level:        int32(user.Level),
		}
		ret = utils.CallbackOkResp(resp)
		return ret, nil
	}
	global.Log.Infof("danmu dont have this kind props.  parameter is  USER ID:=%d, PROPS ID:=%d, QUANTITY:=%d", user.UserId, PropsReq.PropsId, PropsReq.Count)
	return utils.CallbackRespWithCode(imsdk.TIM_SEND_PROPS_ERR, "无此道具", ret), nil
}
